package com.bluestar.tools.module.systemsettings;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.input.InputManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.bluestar.tools.R;
import com.bluestar.tools.common.base.BaseActivity;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.lang.reflect.Method;
import java.util.Calendar;

import androidx.core.content.ContextCompat;

/**
 * @author : lifei
 * 创建时间： 20-6-16
 * 更改时间： 20-6-16
 * Email : allen.lee723@qq.com
 * @version :
 * Description：
 */
public class SystemSettingsActivity extends BaseActivity {

    private QMUITopBarLayout mTopbar;
    private EditText mHourEt;
    private EditText mMinuteEt;
    private EditText mSecondEt;

    private IDSReceiver idsReceiver;

    @Override
    protected int getLayout() {
        return R.layout.activity_system_settings;
    }

    @Override
    protected void initTopbar() {
        mTopbar = findViewById(R.id.topbar);
        mTopbar.setTitle(R.string.system_settings).setTextColor(ContextCompat.getColor(this, R.color.qmui_config_color_white));
        mTopbar.setBackgroundColor(ContextCompat.getColor(this, R.color.qmui_btn_blue_bg));
        mTopbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mHourEt = findViewById(R.id.hour_et);
        mMinuteEt = findViewById(R.id.minute_et);
        mSecondEt = findViewById(R.id.second_et);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (idsReceiver == null) {
            idsReceiver = new IDSReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("hiinfo.intent.action.IDS_WIFI_SETTING");
        registerReceiver(idsReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(idsReceiver);
    }

    private int getHour() {
        String hourStr = mHourEt.getText().toString().trim();
        if (TextUtils.isEmpty(hourStr)) {
            return 0;
        }
        return Integer.parseInt(hourStr);
    }

    private int getMinute() {
        String minuteStr = mMinuteEt.getText().toString().trim();
        if (TextUtils.isEmpty(minuteStr)) {
            return 0;
        }
        return Integer.parseInt(minuteStr);
    }

    private int getSecond() {
        String secondStr = mSecondEt.getText().toString().trim();
        if (TextUtils.isEmpty(secondStr)) {
            return 0;
        }
        return Integer.parseInt(secondStr);
    }

    public void setTime(View view) {
        Log.d(TAG, "setTime: ");
        /*Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, getHour());
        c.set(Calendar.MINUTE, getMinute());
        c.set(Calendar.SECOND, getSecond());
        c.set(Calendar.MILLISECOND, 0);

        long when = c.getTimeInMillis();

        if (when / 1000 < Integer.MAX_VALUE) {
            ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setTime(when);
        }*/

        Calendar c = Calendar.getInstance();
        mHourEt.setText(String.valueOf(c.get(Calendar.HOUR_OF_DAY)));
        mMinuteEt.setText(String.valueOf(c.get(Calendar.MINUTE)));
        mSecondEt.setText(String.valueOf(c.get(Calendar.SECOND)));
    }

    /**
     * 打开系统设置
     */
    public void onClickOpenSystemSettings(View view) {
        // 直接进入手机中的wifi网络设置界面
        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        Log.d(TAG, "openSystemSettings: isChild = " + isChild());

        /*Intent intent = new Intent();
        intent.setClassName("com.android.settings", "com.android.settings.Settings$WifiSettingsActivity");
        startActivity(intent);*/
    }

    /**
     * 关闭屏幕
     */
    public void onClickScreenOff(View view) {
        Log.d(TAG, "screenOff");
        boolean setPowerModeOk;
        IBinder d = SurfaceControl.getBuiltInDisplay();
        if (d == null) {
            Log.e(TAG, "Could not get built-in display");
            setPowerModeOk = false;
        }
        setPowerModeOk = SurfaceControl.setDisplayPowerMode(d, SurfaceControl.POWER_MODE_OFF);
        if (setPowerModeOk) {
            Log.i(TAG, "Device screen turned off");
        }
    }

    /**
     * 回到 Home 界面
     */
    public void onClickHome(View view) {
        injectKeycode(KeyEvent.KEYCODE_HOME);
    }

    /**
     * 点击返回键
     */
    public void onClickBack(View view) {
        injectKeycode(KeyEvent.KEYCODE_BACK);
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
            }
        }).start();*/
    }

    private boolean injectEvent(KeyEvent event) {
        try {
            Log.d(TAG, "sendEvent: ");
            InputManager inputManager;
            Method injectInputEventMethod;
            try {
                inputManager = (InputManager) this.getSystemService(Context.INPUT_SERVICE);
                injectInputEventMethod = inputManager.getClass().getMethod("injectInputEvent", InputEvent.class, int.class);
                Log.d(TAG, "sendEvent: inputManager" + inputManager.hashCode());
            } catch (Exception e) {
                throw new AssertionError(e);
            }
            return (boolean) injectInputEventMethod.invoke(inputManager, event, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean injectKeyEvent(int action, int keyCode, int repeat, int metaState) {
        long now = SystemClock.uptimeMillis();
        KeyEvent event = new KeyEvent(now, now, action, keyCode, repeat, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
            InputDevice.SOURCE_KEYBOARD);
        return injectEvent(event);
    }

    public boolean injectKeycode(int keyCode) {
        return injectKeyEvent(KeyEvent.ACTION_DOWN, keyCode, 0, 0) && injectKeyEvent(KeyEvent.ACTION_UP, keyCode, 0, 0);
    }

    int naviFlag = 0;

    // 点击导航栏按钮
    public void onClickNavigation(View view) {
        // 全屏展示
        if (naviFlag == 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // 全屏显示，隐藏状态栏和导航栏，拉出状态栏和导航栏显示一会儿后消失。
                getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            } else {
                // 全屏显示，隐藏状态栏
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            }
            naviFlag = 1;
        } else {
            // 非全屏显示，显示状态栏和导航栏
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            naviFlag = 0;
        }
    }

    private static class IDSReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, intent.getStringExtra("className"), Toast.LENGTH_SHORT).show();
        }
    }
}